#include "bs_push_streamer.h"

#include<opencv2/opencv.hpp>

#include <yaml-cpp/yaml.h>

/*
    使用bs_push_streamer进行推流的例子
*/

int main(int argc, char **argv)
{
    // 读取yaml配置文件
    /* -----------------------------------------------------*/
    if (argc < 2)
    {
        fmt::print("usage: rtsp_pusher_demo [config]\n");
        return -1;
    }

    std::string config_path = argv[1];

    YAML::Node yaml_cfg;
    try
    {
        yaml_cfg = YAML::LoadFile(config_path);
    }
    catch (YAML::BadFile &e)
    {
        fmt::print("read yaml error!\n");
        return -1;
    }

    std::string name = yaml_cfg["name"].as<std::string>();
    int width = yaml_cfg["width"].as<int>();
    int height = yaml_cfg["height"].as<int>();
    int fps = yaml_cfg["fps"].as<int>();
    int bitrate = yaml_cfg["bitrate"].as<int>();
    std::string encoder = yaml_cfg["encoder"].as<std::string>();

    fmt::print("read yaml OK!\n");
    /* -----------------------------------------------------*/

    // 打开摄像头
    /* -----------------------------------------------------*/
    cv::VideoCapture cap(0); 
    
    if (!cap.isOpened()){
        std::cout << "cv::VideoCapture cap(0) open failed!" << std::endl;
        return -1;
    }
    cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));
    // 设置宽和高为1280x720
    cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
    cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
        
    cv::Mat image;




    // 调用setup进行初始化并使用stream推流
    /* -----------------------------------------------------*/
    BsPushStreamer mBsPushStreamer;

    if (!mBsPushStreamer.setup(name, width, height, fps, encoder, bitrate))
    {
        std::cout << "mBsPushStreamer.start fail!\n";
        return -1;
    }
    std::cout << "mBsPushStreamer.start success!\n";

    auto start_time = std::chrono::steady_clock::now();
    auto cnt_time = std::chrono::steady_clock::now();

    // 推流100s
    while (std::chrono::duration_cast<std::chrono::minutes>(cnt_time - start_time).count() < 10)
    {
        cap.read(image);
        cv::imshow("rtsp_push", image);
        cv::waitKey(1);
        mBsPushStreamer.stream(image);
        

        std::this_thread::sleep_for(std::chrono::milliseconds(1000 / fps));
        cnt_time = std::chrono::steady_clock::now();
    }

    mBsPushStreamer.stop();
    std::cout << "mBsPushStreamer.stop success!\n";
    /* -----------------------------------------------------*/



    return 0;
}
